package com.xbfinal.myzhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbfinal.myzhxy.pojo.Admin;
import com.xbfinal.myzhxy.pojo.LoginForm;
import com.xbfinal.myzhxy.pojo.Student;
import com.xbfinal.myzhxy.pojo.Teacher;
import com.xbfinal.myzhxy.service.AdminService;
import com.xbfinal.myzhxy.service.StudentService;
import com.xbfinal.myzhxy.service.TeacherService;
import com.xbfinal.myzhxy.util.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @autor 笑霸fianl~
 用于：非针对于表格的增删改查的控制
      一些公共的功能写在这儿
     例如 登陆时 对于验证码的校验
 */
@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

//验证码
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response)throws IOException {
        //1.获取图片
        final BufferedImage verifiCodeImage
                = CreateVerifiCodeImage.getVerifiCodeImage();
        //2.获取图片的验证码
        /*final char[] verifiCode
                = CreateVerifiCodeImage.getVerifiCode();*/
        final String verifiCode =
                new String(CreateVerifiCodeImage.getVerifiCode());
        //3.将验证码文本放入session域 为下一次验证做准备
        HttpSession session=request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        //4.将验证码图片相应给浏览器
        final ServletOutputStream outputStream = response.getOutputStream();
       ImageIO.write(verifiCodeImage,"JPEG",outputStream);

    }

//校验登陆是否成功
    @PostMapping("/login")
    public Result Login(@RequestBody LoginForm loginForm,HttpServletRequest request){
        //@RequestBody 前端请求体 提交时json字符串提交过来的
        //@RequestBody的作用其实是将json格式的数据转为java对象。

       //1.验证码是否有效.request来获取验证码
        final HttpSession session = request.getSession();
        final String sessionVerifiCode =(String)session.getAttribute("verifiCode");
        final String loginFormVerifiCode = loginForm.getVerifiCode();
        if("".equals(sessionVerifiCode)|| null == sessionVerifiCode){
            return  Result.fail().message("验证码失效，请刷新");
        }
        if(!(sessionVerifiCode.equalsIgnoreCase(loginFormVerifiCode))){
            return  Result.fail().message("验证码错误！请重输");
        }
        //以上两个条件没满足 说明通过验证码了，然后应该从session中移除验证码(已用失效)
        session.removeAttribute("verifiCode");
        //2.用户类型校验
            //准备一个map用户存放响应数据
        Map<String,Object> map=new LinkedHashMap<>();
        switch(loginForm.getUserType()){
            case 1 ://管理员
                try {
                    Admin admin=adminService.login(loginForm);
                    if(null != admin){
                        //用户类型和用户id转换成一个密文，以token的名称想客户端返回
                        final String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                        map.put("token",token);
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2://学生
                try {
                    Student student=studentService.login(loginForm);
                    if(null!=student){
                        //用户类型和用户id转换成一个密文，以token的名称想客户端返回
                        final String token = JwtHelper.createToken(student.getId().longValue(), 2);
                        map.put("token",token);
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 3://老师
                try {
                    Teacher teacher=teacherService.login(loginForm);
                    if(null!=teacher){
                        //用户类型和用户id转换成一个密文，以token的名称想客户端返回
                        final String token = JwtHelper.createToken(teacher.getId().longValue(), 3);
                        map.put("token",token);
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return  Result.fail().message("没有此用户");
    }

    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){
        //@RequestHeader("token")从请求头获取信息
        //验证token是否过期
        final boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            //如果过期就
            return Result.build(null, ResultCodeEnum.COUPON_GET);
        }
        //从token中解析出id和用户类型
        final Long userId = JwtHelper.getUserId(token);
        final Integer userType = JwtHelper.getUserType(token);
        //判断用户类型
        Map<String,Object> map=new LinkedHashMap<>();
        switch(userType){
            case 1:
               Admin admin=adminService.getAdminById(userId);
               map.put("userType",1);
               map.put("user",admin);
                break;
            case 2:
                Student student=studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher=teacherService.getTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }

        return Result.ok(map);
    }

    @ApiOperation("头像上传统一入口")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("文件二进制数据")
            @RequestPart("multipartFile")
                    MultipartFile multipartFile
    ){
        //使用UUID随机生成文件名
        String uuid =
                UUID.randomUUID()
                        .toString()
                        .replace("-", "")//把-换成空格
                        .toLowerCase();//转小写
        //生成新的文件名字
        String filename = uuid.concat(multipartFile.getOriginalFilename());
        //生成文件的保存路径(实际生产环境这里会使用真正的文件存储服务器)
        String portraitPath
                ="F:\\school\\java\\MyZhxy\\target\\classes\\public\\upload\\".concat(filename);
        //保存文件
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headerImg ="upload/"+filename;
        return Result.ok(headerImg);
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(@RequestHeader("token") String token,
                            @PathVariable("oldPwd") String oldPwd,
                            @PathVariable("newPwd") String newPwd){
        boolean yOn = JwtHelper.isExpiration(token);
        if(yOn){
            //token过期
            return Result.fail().message("token失效!");
        }
        //通过token获取当前登录的用户id
        Long userId = JwtHelper.getUserId(token);
        //通过token获取当前登录的用户类型
        Integer userType = JwtHelper.getUserType(token);
        // 将明文密码转换为暗文
        oldPwd= MD5.encrypt(oldPwd);
        newPwd= MD5.encrypt(newPwd);
        if(userType == 1){
            QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Admin admin = adminService.getOne(queryWrapper);
            if (null!=admin) {
                admin.setPassword(newPwd);
                adminService.saveOrUpdate(admin);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }else if(userType == 2){
            QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Student student = studentService.getOne(queryWrapper);
            if (null!=student) {
                student.setPassword(newPwd);
                studentService.saveOrUpdate(student);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }
        else if(userType == 3){
            QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Teacher teacher = teacherService.getOne(queryWrapper);
            if (null!=teacher) {
                teacher.setPassword(newPwd);
                teacherService.saveOrUpdate(teacher);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }
        return Result.ok();
    }

}
